package cn.taobaoke.restful.controller;

import cn.taobaoke.restful.domain.OrderEntity;
import cn.taobaoke.restful.exception.TBKException;
import cn.taobaoke.restful.service.FileService;
import cn.taobaoke.restful.service.OrderService;
import cn.taobaoke.restful.util.StringUtil;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * @author yangzuo
 * @since 2017-03-29
 */
@RestController
@RequestMapping("/{domain}/{domainId}/api/files")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ExcelFileUploadController extends BaseController {

    @PostMapping("/v1/sync/order")
    public Result synchronizeOrderV1(@PathVariable Long domainId, @PathVariable String domain, @RequestBody List<OrderEntity> orderEntityList) {
        Map<String, Integer> result = orderService.batchStoreOrder(orderEntityList, domainId, domain);
        return wrapObj(result);
    }

    @PostMapping("/v2/sync/order")
    public Result synchronizeOrderV2(@PathVariable Long domainId, @PathVariable String domain, @RequestBody List<Map<String, Object>> data) {

        List<OrderEntity> orderEntityList = new ArrayList<>();
        for (int i = 0; i < data.size(); i++) {
            OrderEntity orderEntity = new OrderEntity();
            Map<String, Object> mapping = data.get(i);
            orderEntity.setCreateTime(StringUtil.stringToDate((mapping.get("createTime")).toString()));
            orderEntity.setClickTime(StringUtil.stringToDate((mapping.get("clickTime")).toString()));
            orderEntity.setCommodityInfo((mapping.get("commodityInfo")).toString());
            orderEntity.setCommodityId((mapping.get("commodityId")).toString());
            orderEntity.setAliWangwang((mapping.get("aliWangwang")).toString());
            orderEntity.setShop((mapping.get("shop")).toString());
            orderEntity.setCommodityNum(StringUtil.stringToInteger((mapping.get("commodityNum")).toString()));
            orderEntity.setCommodityPrice(StringUtil.stringToDouble((mapping.get("commodityPrice")).toString()));
            orderEntity.setOrderStatus((mapping.get("orderStatus")).toString());
            orderEntity.setOrderType((mapping.get("orderType")).toString());
            orderEntity.setIncomeRatio(StringUtil.ratioStringToDouble((mapping.get("incomeRatio")).toString()));
            orderEntity.setShareRatio(StringUtil.ratioStringToDouble((mapping.get("shareRatio")).toString()));
            orderEntity.setPayment(StringUtil.stringToDouble((mapping.get("payment")).toString()));
            orderEntity.setEffectPrediction(StringUtil.stringToDouble((mapping.get("effectPrediction")).toString()));
            orderEntity.setSettlementAmount(StringUtil.stringToDouble((mapping.get("settlementAmount")).toString()));
            orderEntity.setEstimatedIncome(StringUtil.stringToDouble((mapping.get("estimatedIncome")).toString()));
            orderEntity.setSettlementTime((mapping.get("settlementTime")).toString());
            orderEntity.setCommissionRate(StringUtil.ratioStringToDouble((mapping.get("commissionRate")).toString()));
            orderEntity.setCommissionAmount(StringUtil.stringToDouble((mapping.get("commissionAmount")).toString()));
            orderEntity.setSubsidyRatio(StringUtil.ratioStringToDouble((mapping.get("subsidyRatio")).toString()));
            orderEntity.setSubsidyAmount(StringUtil.stringToDouble((mapping.get("subsidyAmount")).toString()));
            orderEntity.setSubsidyType((mapping.get("subsidyType")).toString());
            orderEntity.setTransactionPlatform((mapping.get("transactionPlatform")).toString());
            orderEntity.setThirdParty((mapping.get("thirdParty")).toString());
            orderEntity.setOrderNumber((mapping.get("orderNumber")).toString());
            orderEntity.setCategoryName((mapping.get("categoryName")).toString());
            orderEntity.setMediaId((mapping.get("mediaId")).toString());
            orderEntity.setMediaName((mapping.get("mediaName")).toString());
            orderEntity.setAdPositionId((mapping.get("adPositionId")).toString());
            orderEntity.setPidName((mapping.get("pidName")).toString());
            orderEntityList.add(orderEntity);
        }

        Map<String, Integer> result = orderService.batchStoreOrder(orderEntityList, domainId, domain);
        return wrapObj(result);
    }

    @PostMapping("/excel")
    public Result handleUploadExcelFile(@PathVariable Long domainId, @PathVariable String domain, @RequestParam("file") MultipartFile file) {
        logger.debug("上传文件操作: /{}/api/files/excel", domainId);

        try {
            Map result = fileService.handleExcelFile(file.getInputStream(), file.getOriginalFilename(), domainId, domain);
            return wrapObj(result);
        } catch (IOException e) {
            throw new TBKException("文件上传失败");
        }
    }

    private final @NonNull FileService fileService;

    private final @NonNull OrderService orderService;

    private static Logger logger = LogManager.getLogger(ExcelFileUploadController.class);
}
